<?php

namespace App\Repositories;

use App\Repositories\BaseInterface\Repository;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Support\Facades\Hash;

use Illuminate\Support\Facades\Log;
use App\Utils\LocalStorePath;
use App\Repositories\Contracts\AttachmentRepositoryInterface;
use Spatie\Permission\Models\Role;

class UserRepository extends Repository implements UserRepositoryInterface
{

  public function model()
  {
    return "App\Models\User";
  }

  public function save($data, $id = 0)
  {
    $id = intval($id) > 0 ? intval($id) : 0;
    if (isset($data['password'])) {
      $data['password'] = Hash::make($data['password']);
    }
    $result = $this->createOrUpdate($data, $id);
    $result['roles'] = $result->roles()->pluck('id');
    return $result;
  }

  public function get_user_and_role($userId)
  {
    $user = $this->model->find($userId);
    if (!$user) {
      return null;
    }
    $user->load("roles", "avatar");
    return $user;
  }

  public function save_role($user_id, $roles)
  {
    $user = $this->model->find($user_id);
    if (!$user) {
      return false;
    }

    // 去掉小于0,非整数数据
    $qRoles = array_filter(array_map(function ($v) {
      $v = intval($v) ? intval($v) : 0;
      $v = $v > 0 ? $v : null;
      return $v;
    }, $roles));

    $roleIds = [];

    // 获取已经存在的角色
    if (count($qRoles) > 0) {
      $roleIds = Role::find($roles)->pluck('id');
    }

    $user->roles()->sync($roleIds);
    return true;
  }

  public function avatar($user, $attachment)
  {
    if (!$user || !$attachment) {
      return false;
    }
    //生成缩略图
    Log::debug("生成缩略图");
    $attachmentRepository = app()->make(AttachmentRepositoryInterface::class);
    $fileInfo = new LocalStorePath($attachment->url);
    $result = $attachmentRepository->imageSize($fileInfo, 200, 200, false);
    $info = [];
    if ($attachment->info) {
      $info = $attachment->info;
    }
    $info['tiny_thumbnail']=$result;
    $attachment->info = $info;
    $attachment->save();

    if ($user->avatar()->sync($attachment->id)) {
      return $user->avatar[0];
    };
    return null;
  }
}
